<!-- m_materiel.ftl 存货表 -->
var MMateriel = {
    u: '/mMateriel'
    , uList: '/mMateriel/list'
    , skuList: '/mMateriel/skuList'
    , uEdit: '/mMateriel/edit'
    , uDel: '/mMateriel/delete'
    , uBarcode: '/mMateriel/barcode'
    , uExcel: '/mMateriel/importExcel'
    , uSaveExcel: '/mMateriel/saveExcel'
    , uEditSku: '/mMateriel/sku'
    , skuIdTags: []
    , dgType: undefined
    , winThat: undefined
    , win: undefined
    , dgType2: undefined
    , winThat2: undefined
    , win2: undefined
};

$.extend($.fn.datagrid.defaults.editors, {
    upImage: {
        init: function (container, options) {
            return $('<div>选择</div>').appendTo(container);
        },
        destroy: function (target) {
            $(target).remove();
        },
        getValue: function (target) {
            return $(target).find('img').attr('_path');
        },
        setValue: function (target, value) {
            if (value) $(target).html(MMateriel.getImg(value));
        },
        resize: function (target, width) {
            $(target).click(function () {
                $yd.win.create("图片资源", "/sysPictrue").big().isFrame().open(null, function (that, $win) {
                    var sels = that.innerEle('#picture_table').datagrid('getSelections');
                    if (sels.length > 0) {
                        $(target).html(MMateriel.getImg(sels[0].path));
                    }
                    that.close();
                });
            });

            $(target)._outerWidth(width);
        }
    }
});

MMateriel.getImg = function (path) {
    return '<img src="' + $.urlPre + path + '" _path="' + path + '" style="height: 29px;">';
};
MMateriel.dg = function () {

    //加载价格体系
    $yd.get("/sysDict/materiel_PL", function (data) {
        MMateriel.priceLv = [[]];
        MMateriel.priceLv[0].push(getCol('skus', '规格/尺寸', {align: 'left',editor: 'textbox', width: 300}));
        // MMateriel.priceLv[0].push(getCol('mskuCode', '编码', {align: 'left',editor: 'textbox', width: 150}));
        MMateriel.priceLv[0].push(getCol('partsCode', '配件编码', {align: 'left',editor: 'textbox', width: 150}));
        MMateriel.priceLv[0].push(getCol('buyPrice', '参考进价', {align: 'left', editor: 'textbox', width: 100}));
        MMateriel.priceLv[0].push(getCol('sellPrice', '参考零售价', {align: 'left', editor: 'textbox', width: 100}));
        // MMateriel.priceLv[0].push(getCol('avgBuyPrice', '平均采购进价', {align: 'left', editor: 'textbox', width: 100}));
        // MMateriel.priceLv[0].push(getCol('buyTotalNum', '采购总数量', {align: 'left', editor: 'textbox', width: 100}));
        // MMateriel.priceLv[0].push(getCol('tradePrice', '批发价', {align: 'left', editor: 'textbox', width: 100}));
        // MMateriel.priceLv[0].push(getCol('vip1', '一级会员价', {align: 'left', editor: 'textbox', width: 100}));
        // MMateriel.priceLv[0].push(getCol('vip2', '二级会员价', {align: 'left', editor: 'textbox', width: 100}));
        // MMateriel.priceLv[0].push(getCol('vip3', '三级会员价', {align: 'left', editor: 'textbox', width: 100}));
        // 123级会员价
        $.each(data, function (i, n) {
            MMateriel.priceLv[0].push(getCol(n['value'], n['text'], {align: 'left', editor: 'textbox', width: 100}));
        });
        loadDatagrid();
    });

    // loadDatagrid();
    function getCol(field, title, options) {
        return $.extend({
            field: field,
            title: title,
            width: 120,
            align: 'right',
            resizable: true,
            editor: {type: 'numberbox', options: {precision: 2}}
        }, options);
    }

    function loadDatagrid() {
        var grid = new $yd.DataGrid(MMateriel.dtable);
        grid.onDblClickRow = function (index, row) {
            MMateriel._edit(row['id'],false);
        };
        grid.url = MMateriel.uList;
        grid.onClickRow=function (rowIndex, rowData) {
            $(this).datagrid('unselectRow', rowIndex);
        }
        // grid.autoSizeColumn = "img";
        grid.nowrap = false;
        grid.checkOnSelect = false;
        grid.rownumbers = true;
        grid.columns = [[
            {field: 'id', checkbox: true}
            , {field: 'name', title: '名称', width: 100}
            , {field: 'ctime', title: '创建时间', width: 100}
            , {field: 'categoryName', title: '分类', width: 50}
            , {field: 'brandName', title: '品牌', width: 50}
            , {field: 'relativeName', title: '默认供应商', width: 100}
            , {field: 'car', title: '适用车型', width: 100, formatter: function (value) {
                return $yd.formatDetail(value);
                }
            }
            // , {field: 'min_inventory', title: '最低库存', width: 50}
            // , {field: 'max_inventory', title: '最高库存', width: 50}
            // , {
            //     field: 'status', title: '状态', width: 50, formatter: function (value) {
            //         if (value == 0) {
            //             return '<label class="label label-success">启用</label>';
            //         } else if (value == 1){
            //             return '<label class="label label-default">禁用</label>';
            //         }
            //     }
            // }
            // , {field: 'skus', title: '规格', width: 100}
            // , {field: 'mskuCode', title: '编码', width: 100}

        ]];
        grid.view = detailview;
        grid.detailFormatter = function (rowIndex, rowData) {
            return '<table></table>';
        };
        grid.rowStyler = function (index, row) {
            if (row.status != 0) {
                return {class: 'text-muted', style: 'text-decoration:line-through'};
            }
        };
        grid.onExpandRow = function (index,row) {
            var $td = $(this).datagrid('getRowDetail', index).find('table');
            $td.datagrid({
                rownumbers : true,
                url : MMateriel.skuList +"?id="+row['id'],
                columns:MMateriel.priceLv,
                onResize: function () {
                    MMateriel.dtable.datagrid('fixDetailRowHeight', index);
                },
                onLoadSuccess: function () {

                    setTimeout(function () {
                        MMateriel.dtable.datagrid('fixDetailRowHeight', index);
                    }, 0);
                }
            });

            
        }
        // grid.columns = MMateriel.priceLv;
        grid.loadFilter = function (data) {
            MMateriel.dg.merges = {};
            data.rows = data.records;
            $.each(data.rows, function (i, n) {
                if (n.prices) $.extend(n, JSON.parse(n.prices));
                var mid = MMateriel.dg.merges[n['id']];
                if (mid == undefined) {
                    MMateriel.dg.merges[n['id']] = {index: i, rows: 1};
                } else {
                    mid.rows = mid.rows + 1;
                }
            });
            return data;
        };
        grid.onLoadSuccess = function () {
            var $this = $(this);
            $.each(MMateriel.dg.merges, function (key, value) {
                var merge = {index: value.index, field: 'name', rowspan: value.rows};
                $this.datagrid('mergeCells', merge)
                    .datagrid('mergeCells', $.extend(merge, {field: 'id'}))
                    .datagrid('mergeCells', $.extend(merge, {field: 'categoryName'}))
                    .datagrid('mergeCells', $.extend(merge, {field: 'relativeName'}))
                    .datagrid('mergeCells', $.extend(merge, {field: 'max_inventory'}))
                    .datagrid('mergeCells', $.extend(merge, {field: 'min_inventory'}))
                    .datagrid('mergeCells', $.extend(merge, {field: 'car'}))
                    .datagrid('mergeCells', $.extend(merge, {field: 'status'}))
                    .datagrid('mergeCells', $.extend(merge, {field: 'brandName'}))
                    // .datagrid('mergeCells', $.extend(merge, {field: 'ainventory'}))
                    .datagrid('mergeCells', $.extend(merge, {field: 'ctime'}))
                ;
            });
        };/*
        grid.onEndEdit = function (index, row, changes) {
            var $this = $(this);
            if (changes) {
                // $yd.confirm("确定修改？", function () {
                //
                // })
                var sku = {};
                $.each(MMateriel.priceLv[0], function (i, n) {
                    sku[n.field] = row[n.field];
                });
                var _sku = $.extend(true, {}, sku);
                delete _sku['skus'];
                delete _sku['inventory'];
                sku.prices = JSON.stringify(_sku);
                sku.id = row.skuId;
                sku.mid = row.id;
                $yd.post(MMateriel.uEditSku, sku, function () {
                    $this.datagrid('reload');
                });
            }
        };*/
        grid.loadGrid();
        // MMateriel.dtable.datagrid('enableCellEditing');
    }
};
MMateriel.dg.getOne = function () {
    var sels = MMateriel.dg.getSels();
    if (sels.length === 1) {
        return sels[0];
    }
    return null;
};
MMateriel.dg.getSels = function () {
    return MMateriel.dtable.datagrid('getSelections');
};
MMateriel.lcxxdd = function() {
    var sel = MMateriel.dg.getOne();
    if (!sel) {
        $yd.alert('请选择一条记录');
        return;
    }
    parent.inv.OpenPage("/mSales?searchText=" + sel.name, "<i class=\"menu-icon fa fa-flag\"></i>\n" +
        "<span class=\"menu-text\">销售单列表</span>\n" +
        "<b class=\"arrow \"></b>", true)
};
MMateriel.lccgd = function() {//采购单
    var sel = MMateriel.dg.getOne();
    if (!sel) {
        $yd.alert('请选择一条记录');
        return;
    }
    parent.inv.OpenPage("/pPurchase?searchText=" + sel.name, "<i class=\"menu-icon fa fa-flag\"></i>\n" +
        "<span class=\"menu-text\">采购单列表</span>\n" +
        "<b class=\"arrow \"></b>", true)
};

MMateriel.lckcl = function() {//库存量
    var sel = MMateriel.dg.getOne();
    if (!sel) {
        $yd.alert('请选择一条记录');
        return;
    }
    parent.inv.OpenPage("/repositoryCount?searchText=" + sel.name, "<i class=\"menu-icon fa fa-flag\"></i>\n" +
        "<span class=\"menu-text\">库存量查询</span>\n" +
        "<b class=\"arrow \"></b>", true)
};
// 处理按钮
MMateriel.btn = function () {
    var sb = new $yd.SearchBtn($(MMateriel.obtn));
    sb.create('remove', '删除(DEL)', MMateriel.remove);
    // sb.create('barcode green', '条码', MMateriel.barcode);
    sb.create('print green', '打印', function () {
        MMateriel.dtable.datagrid('print', '存货表');
    });
    sb.create('file-excel-o green', '导出', function () {
        MMateriel.dtable.datagrid('toExcel', '存货表.xls');
    });
    sb.create('file-excel-o green', '导入', MMateriel.importExcel);
    sb.create('file-excel-o green', '下载导入模板', MMateriel.downLoadTemplet);
    sb.create('refresh', '刷新(F2)', MMateriel.refresh);
    // sb.create('files-o', '复制', MMateriel.copy);
    // sb.create('edit', '编辑', MMateriel.edit);
    sb.create('plus', '新增(Shift+N)', MMateriel.plus);
    // sb.create('search', '查询', MMateriel.search);

    $("#lcxxdd").click(MMateriel.lcxxdd);
    $("#lcptdd").click(MMateriel.lcptdd);
    $("#lccgd").click(MMateriel.lccgd);
    $("#lckcl").click(MMateriel.lckcl);
};
MMateriel.copy = function () {
    MMateriel.edit(true);
};
//删除
MMateriel.remove = function () {
    var sels = MMateriel.dg.getSels();
    if (!sels || sels.length < 1) {
        $yd.alert('请选中记录');
        return;
    }
    $yd.confirm(function () {
        var ids = [];
        $.each(sels, function (i, n) {
            ids.push(n['id']);
        });
        $yd.post(MMateriel.uDel, {ids: ids}, function () {
            MMateriel.search();
        });
    })
};
// 生成条码
MMateriel.barcode = function () {
    var sel = MMateriel.dg.getOne();
    if (!sel) {
        $yd.alert('请选择一条记录');
        return;
    }
    $yd.win.create('条码', MMateriel.uBarcode + "?id=" + sel['id']).open(function (that, $win) {
        // 添加图片元素
        var ids = $("#skuIds").val().split(",");
        for (var i=0; i<ids.length; i++) {
            if (!$yd.isEmpty(ids[i])) {
                var img =
                    '<div class="col-sm-4">'
                    + '<img src="/mMateriel/generateBarcode?id=' + ids[i]
                    + '"></div>';
                $("#barcode").append(img);
            }
        }
    });
};
// 下载导入模板
MMateriel.downLoadTemplet = function () {
    location.href="/mMateriel/downLoadTemplet";
}
// 导入
MMateriel.importExcel = function () {
    $yd.win.create('导入Excel', MMateriel.uExcel).open(function (that, $win) {

        }, function (that, $win) {
            $yd.form.create($win.find('form')).url(MMateriel.uSaveExcel).submit(function () {
                that.close();
                MMateriel.refresh();
            });
        }
    );
}

// 编辑
MMateriel.edit = function (isCopy) {
    var sel = MMateriel.dg.getOne();
    if (!sel) {
        $yd.alert('请选择一条记录');
        return;
    }
    MMateriel._edit(sel['id'], isCopy);
};
MMateriel.onClickCell = function () {

};

$.extend($.fn.datagrid.defaults.editors, {
    myDate: {
        init: function (container, options) {
            return $('<input id="attYearMonth" editable="false" name="attYearMonth" class="easyui-datebox" style="width: 100%" />').appendTo(container);
        },
        destroy: function (target) {
            $(target).remove();
        },
        getValue: function (target) {
            return  $('#attYearMonth').datebox("getValue");
        },
        setValue: function (target, value) {
            if($yd.isEmpty(value)) {
                $('#attYearMonth').datebox("setValue", (new Date().getFullYear() - 3) + "-" + (new Date().getMonth() + 1));
            } else {
                $('#attYearMonth').datebox("setValue", value);
            }
        },
        resize: function (target, width) {
            $('#attYearMonth').datebox({
                //显示日趋选择对象后再触发弹出月份层的事件，初始化时没有生成月份层
                onShowPanel: function () {
                    //触发click事件弹出月份层
                    var p = $('#attYearMonth').datebox('panel'),
                        //日期选择对象中月份
                        tds = false,
                        //显示月份层的触发控件
                        span = p.find('span.calendar-text');

                    span.trigger('click');
                    if (!tds)
                    //延时触发获取月份对象，因为上面的事件触发和对象生成有时间间隔
                        setTimeout(function() {
                            tds = p.find('div.calendar-menu-month-inner td');
                            tds.click(function(e) {
                                //禁止冒泡执行easyui给月份绑定的事件
                                e.stopPropagation();
                                //得到年份
                                var year = /\d{4}/.exec(span.html())[0] ,
                                    //月份
                                    //之前是这样的month = parseInt($(this).attr('abbr'), 10) + 1;
                                    month = parseInt($(this).attr('abbr'), 10);

                                //隐藏日期对象
                                $('#attYearMonth').datebox('hidePanel')
                                //设置日期的值
                                    .datebox('setValue', year + '-' + month);
                            });
                        }, 0);
                },
                //配置parser，返回选择的日期
                parser: function (s) {
                    if (!s) return new Date();
                    var arr = s.split('-');
                    return new Date(parseInt(arr[0], 10), parseInt(arr[1], 10) - 1, 1);
                },
                //配置formatter，只返回年月 之前是这样的d.getFullYear() + '-' +(d.getMonth());
                formatter: function (d) {
                    var currentMonth = (d.getMonth()+1);
                    var currentMonthStr = currentMonth < 10 ? ('0' + currentMonth) : (currentMonth + '');
                    return d.getFullYear() + '-' + currentMonthStr;
                }
            });

            $(target)._outerWidth(width);
        }
    }
});

// 表单预处理
MMateriel.initPriceTab = function () {
    if (!MMateriel.initPriceTab.isInit) {
        MMateriel.priceLv[0].push({
            field: 'img', title: '图片', width: 60, editor: 'upImage', formatter: function (value) {
                if (value)  return MMateriel.getImg(value);
                return '';
            }
        });
        MMateriel.initPriceTab.isInit = true;
    }

    drawPriceTab();
    var editIndex = -1;

    function drawPriceTab() {
        MMateriel.ptable = $('#priceTab');
        MMateriel.ptable.datagrid({
            fitColumns: true,
            autoRowHeight: true,
            rownumbers: true,
            singleSelect: true,
            columns: MMateriel.priceLv,
            toolbar: [
                {text: '提取组合', iconCls: 'icon-reload', handler: convertSku},
                '-',
                {text: '增加', iconCls: 'icon-add', handler: appendRow},
                {
                    text: '移除', iconCls: 'icon-remove', handler: function () {
                        if (editIndex == -1) return;
                        MMateriel.ptable.datagrid('cancelEdit', editIndex).datagrid('deleteRow', editIndex);
                        editIndex = -1;
                    }
                },
                {
                    text: '确定', iconCls: 'icon-save', handler: function () {
                    MMateriel.ptable.datagrid('acceptChanges').datagrid('clearSelections');
                }
                },
                {
                    text: '取消', iconCls: 'icon-undo', handler: function () {
                        MMateriel.ptable.datagrid('rejectChanges');
                        editIndex = -1;
                    }
                }],
            onClickCell: function (index, field, value) {
                if (editIndex != index) {
                    editIndex = index;
                }
                // 以前的规格名称不允许编辑
                var rows = $(this).datagrid('getRows');
                var row = rows[index];
                if (!$yd.isEmpty(row['id'])) {
                    // if (field == 'skus' ) {
                    //     $(this).datagrid('endEdit', index);
                    //     $yd.alert("已存在规格名称不可修改");
                    //     return;
                    // } else {
                        // var e = MMateriel.ptable.datagrid('getColumnOption', 'skus');
                        // e.editor = {};
                        // $(this).datagrid('removeEditor', 'skus');
                    // }
                } else {
                    $(this).datagrid('addEditor', {
                        field : 'skus',
                        editor : {
                            type : 'textbox'
                        }
                    });
                }
                if (editIndex != index) {
                    if (editIndex > -1) {
                        $(this).datagrid('endEdit', editIndex);
                    }
                    // editIndex = index;
                }
                $(this).datagrid('beginEdit', index);
                var ed = $(this).datagrid('getEditor', {index: index, field: field});
                if (ed) {
                    ($(ed.target).data('textbox') ? $(ed.target).textbox('textbox') : $(ed.target)).focus();
                }
            }
        }).parent().keyup(function (event) {
            if (event.keyCode == 13) {
                MMateriel.ptable.datagrid('acceptChanges').datagrid('clearSelections');
            }
            if (event.keyCode == 40) {
                appendRow();
            }
        });
    }

    // 提取规格型号
    function convertSku() {
        var arr1 = [];
        var arr2 = [];
        if (MMateriel.skuIdTags.length == 0) {
            $yd.alert("当前分类没有关联规格，请在分类管理里面配置");
            return false;
        }
        $.each(MMateriel.skuIdTags, function (i, n) {
            if (arr1.length == 0) {
                $.each($(n['id']).tagbox('getValues'), function (i, nn) {
                    arr1.push(n['name'] + ":" + nn);
                });
            } else {
                $.each(arr1, function (i, nn) {
                    $.each($(n['id']).tagbox('getValues'), function (i, nnn) {
                        arr2.push(nn + " " + n['name'] + ":" + nnn);
                    });
                });
                arr1 = arr2;
                arr2 = [];
            }
        });
        // console.log("规格提取结果：" + JSON.stringify(arr1));

        if (arr1.length > 0) {
            var rows = MMateriel.ptable.datagrid('getRows');
            var eJson = {};
            if (rows.length > 0) { // 匹配并加载
                $yd.confirm("将覆盖现有规格？", function () {
                    $.each(rows, function (i, n) {
                        eJson[n.skus] = n;
                    });
                    MMateriel.ptable.datagrid('loadData', []);
                    $.each(arr1, function (i, n) {
                        MMateriel.ptable.datagrid('appendRow', $.extend({inventory: 0}, eJson[n], {skus: n}));
                    })
                })
            } else { // 直接加载自由项
                $.each(arr1, function (i, n) {
                    MMateriel.ptable.datagrid('appendRow', {skus: n, inventory: 0});
                })
            }
        }
    }

    function appendRow() {
        if (editIndex > -1) {
            MMateriel.ptable.datagrid('acceptChanges').datagrid('cancelEdit', editIndex);
        }
        MMateriel.ptable.datagrid('appendRow', {inventory: 0}).datagrid('clearSelections');
        editIndex = MMateriel.ptable.datagrid('getRows').length - 1;
        MMateriel.ptable.datagrid('beginEdit', editIndex);
        var ed = MMateriel.ptable.datagrid('getEditor', {index: editIndex, field: 'skus'});
        if (ed) {
            ($(ed.target).data('textbox') ? $(ed.target).textbox('textbox') : $(ed.target)).focus();
        }
    }


    // $("#goodsTb").tree({
    //     url: '/carBrand/tree',
    //     cascadeCheck: false,
    //     checkbox: true,
    //     onCheck: function (node, checked) {
    //         if(checked == true) {
    //
    //         }
    //     }
    // });

    drawCarTab();
    var editIndex2 = -1;

    function drawCarTab() {
        MMateriel.ctable = $('#carTab');
        MMateriel.ctable.datagrid({
            url: "/carBrandMateriel/getDetailList?materielId=" + $("#id").val(),
            fitColumns: true,
            autoRowHeight: true,
            rownumbers: true,
            singleSelect: false,
            columns: [[
                {field: 'id', checkbox: true},//
                {field: 'carBrandId', hidden: true},//
                {field: 'car', title: '车型', width: 150, formatter: function (value, row, index) {
                    if(!Array.isArray(value)) {
                        value = $.parseJSON(value);
                    }
                    var result = "";
                    for(var i=0; i<value.length; i++) {
                        result += " -> " + value[i].name;
                    }
                    if(result != "") {
                        result = result.substr(4);
                    }
                    return result;
                }},
                {field: 'year', title: '出厂年月', width: 150,
                    editor: {type: 'myDate'}
                }
            ]],
            toolbar: [
                {text: '增加', iconCls: 'icon-add', handler: appendCar},
                {text: '移除', iconCls: 'icon-remove', handler: removeCar},
                {
                    text: '确定', iconCls: 'icon-save', handler: function () {
                        if (editIndex2 > -1) {
                            MMateriel.ctable.datagrid('endEdit', editIndex2);
                        }
                        editIndex2 = -1;
                    }
                }
                ],
            onClickCell: function (index, field) {
                if (editIndex2 != index) {
                    if (editIndex2 > -1) {
                        MMateriel.ctable.datagrid('endEdit', editIndex2);
                    }
                    editIndex2 = index;
                }
                if (field == "year") {
                    MMateriel.ctable.datagrid('beginEdit', index);
                }
            }
        });

        MMateriel.ctable.datagrid('enableCellEditing');
    }

    function appendCar() {
        var href = "/carBrand/tree?type=0";
        var $dg = $yd.win2.create('车型', href);
        $dg.width = "450px;";
        $dg.height = "520px;";

        MMateriel.dgType2 = "car";
        $dg.open(function (that, $win) {
            MMateriel.win2 = $win;
            MMateriel.winThat2 = that;
        }, function () {
            MMateriel.saveCarBrand();
        }, function () {
            MMateriel.closeDg2(1);
        });
    }
    
    function removeCar() {
        var rows = MMateriel.ctable.datagrid('getChecked');
        if(rows.length == 0) {
            $yd.alert("选中记录");
            return;
        }

        var arr = [];
        for(var i=0; i<rows.length; i++) {
            arr[i] = rows[i].carBrandId;
        }
        for(var i=0; i<arr.length; i++) {
            var rows2 = MMateriel.ctable.datagrid("getRows");
            for(var j=0; j<rows2.length; j++) {
                if(rows2[j].carBrandId == arr[i]) {
                    MMateriel.ctable.datagrid("deleteRow", j);
                    break;
                }
            }
        }
    }
};
MMateriel.saveCarBrand = function() {
    var result = CarTree.getChecked();
    for(var i=0; i<result.length; i++) {
        var arr = result[i];
        var carBrandId = arr.length == 0 ? 0 : arr[arr.length-1].id;
        MMateriel.ctable.datagrid('appendRow', {
            car: arr,
            carBrandId: carBrandId
        }).datagrid('clearSelections');
    }
    MMateriel.closeDg2(0)
};
MMateriel.cateChange = function (newValue, oldValue) {
    $('#skuContainer').html('');
    MMateriel.skuIdTags = [];
    $yd.get("/mCateogry/msku?categoryId=" + newValue, function (data) {
        if (data.length == 0) {
            $('#m_tabs').tabs('unselect', 1).tabs('disableTab', 1);
            return;
        }
        $('#m_tabs').tabs('enableTab', 1);
        $.each(data, function (i, n) {
            var id = 'sku_' + n['sku_id'];
            var $input = '<div class="form-group"><label class="col-sm-2 control-label">' + n['name'] + '</label><div class="col-sm-8"><input id="' + id + '" type="text" style="width:100%;"></div></div>';
            $('#skuContainer').append($input);
            MMateriel.skuIdTags.push({id: '#' + id, name: n['name']});// 存储规格标签
            $('#' + id).tagbox({
                url: '/mSkuValue/allList?status=0&skuId=' + n['sku_id'],
                valueField: 'name',
                textField: 'name',
                method: 'get',
                panelHeight: 'auto',
                prompt: '输入规格值，无规格值不能提取组合',
                // limitToList: true,
                hasDownArrow: true,
                loadFilter: function (data) {
                    $.each(data['data'], function (i, n) {
                        if (n['isDefault']) {
                            $('#' + id).tagbox('setValue', {name: n['name']});
                        }
                    });
                    return data['data'];
                }
            });
        })
    });

};
// 存货分类：只能单选且只能选子节点
/*
MMateriel.initCategoryTree = function () {
    $("#categoryId").combotree({
        method: 'get',
        url: '/mCateogry/tree',
        multiple: false,//当为true时，为多选，false为单选
        checkbox: false,
        onlyLeafCheck: true,//当为多选时，起作用，只允许选择叶子节点
        onSelect: function (node) {//当为单选时，只允许选择叶子节点的设置
            //返回树对象
            var tree = $(this).tree;
            //选中的节点是否为叶子节点,如果不是叶子节点,清除选中
            var isLeaf = tree('isLeaf', node.target);
            if (!isLeaf) {
                //清除选中
                // tree('uncheck');
                tree('uncheck', node.target);
            }
        }

    });
}*/
MMateriel.saveKwSet = function() {
    var data = KW.getResult();
    if (data == "") {
        $("#defaultWhouseId").textbox("setValue", "");
        $("#house").val("");
    } else {
        var arr = data.split(",");
        var tmp = "";
        for (var i = 0; i < arr.length; i++) {
            tmp += ";" + arr[i].split("_")[1];
        }
        if (tmp != "") {
            tmp = tmp.substr(1);
        }
        $("#house").val(data);
        $("#defaultWhouseId").textbox("setValue", tmp);
    }
    MMateriel.closeDg2(0)
};

//新增库位
MMateriel.plusKw = function () {
    MMateriel.dgType2 = "position";
    var dg = $yd.win2.create('新增库位', "/wPosition/edit");
    dg.width = "500px";
    dg.height = "400px";
    dg.open(function (that, $win) {
            MMateriel.win2 = $win;
            MMateriel.winThat2 = that;
            // new $yd.combotreegrid("#wearhouseId").addCol("name", "名称").addCol("code", "编码").load("/wWearhouse/listForAvailable");
        }, function () {
            MMateriel.saveKw();
        }, function () {
            MMateriel.closeDg2(1);
        } , function () {
            MMateriel.saveKwNext();
        }
    );
};
MMateriel.saveKw = function () {
    $yd.form.create(MMateriel.win2.find('form')).url("/wPosition").submit(function () {
        MMateriel.closeDg2(0);
    });
};
MMateriel.saveKwNext = function () {
    $yd.form.create(MMateriel.win2.find('form')).url("/wPosition").submit(function () {
        WPositionEdit.reset();
    });
};
//表单预处理
MMateriel.preForm = function (data,isPlus) {
    // MMateriel.initCategoryTree();
    // if (isPlus || $("#hiddenCategoryId").val() == 0) {
        var category = new $yd.combotreegrid("#categoryId",true).addCol('name', '名称').addCol('code', '编码');
        // category.onChange = MMateriel.cateChange;
        category.load("/mCateogry/list?status=0");
    // }


    new $yd.combogrid('#brandId').addCol('name', '名称').load('/mBrand/list?status=0');
    new $yd.combogrid('#defaultUintId').addCol('name', '名称').addCol('code', '编码').load('/wRelativeUnit/list?rproperty=2&status=0');


    var materielId = $("#id").val();
    if (materielId != null && materielId != "" && materielId != undefined) {
        $yd.post("/wPositionMateriel/getBindInfo", {materielId: materielId}, function (data) {
            if (data == "") {
                return;
            }
            var arr = data.split(",");
            var tmp = "";
            for (var i = 0; i < arr.length; i++) {
                tmp += ";" + arr[i].split("_")[1];
            }
            if (tmp != "") {
                tmp = tmp.substr(1);
            }
            $("#house").val(data);
            $("#defaultWhouseId").textbox("setValue", tmp);
        });
    }

    $("#houseSet").click(function () {
        $("#defaultWhouseId").next().find(".textbox-text").focus();//避免设置链接enter键位保存后再次触发

        MMateriel.dgType2 = "kw";
        var href = "/wWearhouse/treeGridBind?materielId=" + materielId + "&house=" + $("#house").val();
        var $dg = $yd.win2.create('仓库/库位', href);
        $dg.width = "450px;";
        $dg.height = "520px;";
        $dg.addBtn("新增库位", "icon-add", function () {
            MMateriel.closeDg2(0);
            MMateriel.plusKw();
        });
        $dg.open(function (that, $win) {
            MMateriel.win2 = $win;
            MMateriel.winThat2 = that;
        }, function () {
            MMateriel.saveKwSet();
        }, function () {
            MMateriel.closeDg2(1);
        });
    });
    this.initPriceTab();

    //图片详情
    MMateriel._picDesc = new $yd.picDesc('#pic_desc_container');

    if (data) {
        $.each(data['mSkus'], function (i, n) {
            if (n['prices']) {
                $.extend(n, JSON.parse(n['prices']));
                delete n['prices'];
            }
        });
        MMateriel.ptable.datagrid('loadData', data['mSkus']);
        //图片处理.
        MMateriel.pictrues = new $yd.fileinput('#pictrues').render(data['pictrues']);
        //描述
        // $('#description').texteditor('setValue', data['description']);
        MMateriel._picDesc.setValue(data['description']);
        console.log("description:"+data['description']);
    } else {
        console.log("进了else");
        MMateriel.pictrues = new $yd.fileinput('#pictrues').render();
    }

    // $('#categoryId').combotree("setText",data['categoryName']);
    setTimeout(function () {
        hehe(data)
    },300);
    var hehe = function (data) {
        if (MMateriel.notBlank(data) && MMateriel.notBlank(data['categoryName'])){
            $('#categoryId').combotreegrid("setText",data['categoryName']);
        }
    }
};

MMateriel.notBlank = function (data) {
    if (data != null && data != undefined && data != '') {
        return true;
    }
    return false
}

// 提交数据
//处理规格
MMateriel.pre = function (param) {



    MMateriel.ptable.datagrid('acceptChanges');
    MMateriel.ctable.datagrid('acceptChanges');
    var rows = MMateriel.ptable.datagrid('getRows');
    var flag = false;
    var flag1 = false;
    // param.ainventory = 0;
    $.each(rows, function (i, n) {
        console.log(n);
        console.log(n['1']);
        if (!n['buyPrice']){
            flag = true;
        }
        if (!n['0']) {
            flag1 = true;
        }
        if (n) {
            // param.ainventory += parseFloat(n['inventory']) || 0;
            // var _n = $.extend(true, {}, n);
            // delete _n['id'];
            // delete _n['skus'];
            // delete _n['inventory'];
            // delete _n['buyPrice'];
            // delete _n['sellPrice'];
            // n.prices = JSON.stringify(_n);
            // 价格信息json
            var prices = {0:n['0'],1:n['1'],2:n['2'],3:n['3']};
            n.prices = JSON.stringify(prices);
        };
    });

    // if (flag) {
    //     $yd.alert("请完善规格信息，进价是必填项.");
    //     return true;
    // }
    if (flag1) {
        $yd.alert("请完善规格信息，批发价是必填项.");
        return true;
    }
    param.mMaterielSkuStr = JSON.stringify(rows);
    param.pictrues = MMateriel.pictrues.getValues();
    param.description = MMateriel._picDesc.getValue();

    param.carBrand = JSON.stringify(MMateriel.ctable.datagrid('getRows'));
};
MMateriel._edit = function (id, isCopy) {
    MMateriel.dgType = "goods";

    $yd.win2.create('编辑存货', MMateriel.uEdit + '?id=' + id).big().open(function (that, $win) {
            // MMateriel.preFormCa($win.find('form'));
            MMateriel.win = $win;
            MMateriel.winThat = that;
            $yd.get(MMateriel.u + "/" + id, function (data) {
                $win.find('form').form('load', data);
                MMateriel.preForm(data,false);
                // MMateriel.cateChange($('input[name="categoryId"]').val());
                // if (isCopy) {
                //     $win.find('input[name="id"]').val("");
                // }
            })

        }, function () {
            MMateriel.save();
        }, function () {
            MMateriel.closeDg(1);
        }
    );
};
MMateriel.save = function() {
    $yd.form.create(MMateriel.win.find('form')).url(MMateriel.u).pre(MMateriel.pre).submit(function () {
        MMateriel.closeDg(0);
        MMateriel.refresh();
    });
};
//新增
MMateriel.plus = function () {
    MMateriel.dgType = "goods";

    var sel = MMateriel.dg.getOne();
    var href = MMateriel.uEdit;
    if (sel) href += '?pid=' + sel['id'] + '&name=' + sel['name'];
    $yd.win2.create('新增存货', href).big().open(function (that, $win) {
            MMateriel.win = $win;
            MMateriel.winThat = that;
            MMateriel.preForm(null,true);
        }, function () {
            MMateriel.save();
        }, function () {
            MMateriel.closeDg(1);
        }
    );
};
MMateriel.closeDg = function (closeEd) {
    if(closeEd == 0) {
        MMateriel.winThat.close();
    }

    MMateriel.dgType = undefined;
    MMateriel.winThat = undefined;
    MMateriel.win = undefined;
};
MMateriel.closeDg2 = function (closeEd) {
    if(closeEd == 0) {
        MMateriel.winThat2.close();
    }

    MMateriel.dgType2 = undefined;
    MMateriel.winThat2 = undefined;
    MMateriel.win2 = undefined;
};
MMateriel.keyUp = function (event) {
    var e = event || window.event || arguments.callee.caller.arguments[0];
    if (!e) {
        return;
    }
    // console.log(e.keyCode);
    if($yd.isForbidCutKey == 1) {
        return;
    }
    if($yd.isEmpty(MMateriel.dgType)) { //未弹框
        if (e.shiftKey && e.keyCode == 78) { //Shift+N
            MMateriel.plus();
        }
        if (e.shiftKey && e.keyCode == 69) { //Shift+E
            MMateriel.edit();
        }
        if(e.keyCode == 113) {//F2
            MMateriel.refresh();
        }
        if(e.keyCode == 46) {//DEL
            MMateriel.remove();
        }
        if(e.keyCode == 13) {
            MMateriel.search();
        }
    } else{ //弹框
        if(e.keyCode == 27) {//ESC
            if(!$yd.isEmpty(MMateriel.dgType2)) {
                MMateriel.closeDg2(0);
            } else {
                MMateriel.closeDg(0);
            }
        }
        if(e.keyCode == 13) {//Enter
            if(!$yd.isEmpty(MMateriel.dgType2)) {
                if(MMateriel.dgType2 == "car") {
                    MMateriel.saveCarBrand();
                } else if(MMateriel.dgType2 == "kw") {
                    MMateriel.saveKwSet();
                } else if(MMateriel.dgType2 == "position") {
                    if(e.ctrlKey) {
                        MMateriel.saveKwNext();
                    } else {
                        MMateriel.saveKw();
                    }
                }
            } else  {
                MMateriel.save();
            }
        }
    }
};
MMateriel.init = function () {
    //快捷键
    document.onkeyup = MMateriel.keyUp;

    //先获取焦点再失去焦点，否则打开页面后若不点击页面，快捷键无效
    $("#searchText").next().find(".textbox-text").focus()
    $("#searchText").next().find(".textbox-text").blur()
};
//
MMateriel.refresh = function () {
    // $('#mMateriel_table').datagrid('unselectAll');
    // MMateriel.dtable.datagrid('reload');
    var node = MMateriel.categoryTree.tree("getSelected");
    if(node) {
        MMateriel.categoryTree.treeLoadId = node.id;
    } else {
        MMateriel.categoryTree.treeLoadId = undefined;
    }

    MMateriel.categoryTree.tree("reload");
};
//搜索
MMateriel.search = function () {
    MMateriel.dtable.datagrid('load', MMateriel.sform.serializeObject());
};
MMateriel.ctree = function () {
    MMateriel.categoryTree = $('#mCateogry_tree');
    MMateriel.categoryTree.tree({
        url: '/mCateogry/treeAll',
        method: 'get',
        onClick: function (node) {
            MMateriel.dtable.datagrid('reload', {categoryId: node.id});
        },
        onLoadSuccess: function () {
            if(MMateriel.categoryTree.treeLoadId) {
                var node = MMateriel.categoryTree.tree("find", MMateriel.categoryTree.treeLoadId);
                if(node) {
                    MMateriel.categoryTree.tree("expandTo", node.target);
                    MMateriel.categoryTree.tree("select", node.target);
                    MMateriel.dtable.datagrid('reload', {categoryId: node.id});
                }
            } else {
                MMateriel.dtable.datagrid('reload');
            }
        }
    });
};
$(function () {
    MMateriel.sform = $('#mMateriel_form');
    MMateriel.dtable = $('#mMateriel_table');
    MMateriel.obtn = '#mMateriel_btn';

    MMateriel.dg(); // 数据表格
    MMateriel.btn(); // 初始化按钮
    $yd.bindEnter(MMateriel.search);
    MMateriel.ctree();  //存货分类树
    $("#searchButton").click(MMateriel.search);

    MMateriel.init();

    if(!$yd.isEmpty($("#hidSearchText").val())) {
        $("#searchText").textbox("setValue", $("#hidSearchText").val());
        setTimeout("MMateriel.search()", 500);
    }
});


